from server import db, api_auth, user_opt
from flask import jsonify, Blueprint, request, g
from server.model.m_dict import Dict
from server.model import set_field, query_by_field
import math

r_dict = Blueprint('dict', __name__)


@r_dict.route('', methods=['GET'])
@api_auth.login_required
def get_dicts():
    """
                    @@@
                    #### Args:
                           {
                                page: 1,
                                limit: 20,
                                filter: {},
                                start_time: "2021-09-10",
                                end_time: "2021-09-12",
                            }
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in dict_list],
                            }
                """
    page = request.args.get('page', type=int, default=1)
    limit = request.args.get('limit', type=int, default=20)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    query_filter = request.args.get('filter')

    try:

        dict_list = Dict.query

        if query_filter:
            dict_list = query_by_field(dict_list, query_filter, Dict)

        if start_time:
            dict_list = dict_list.filter(db.cast(Dict.create_time, db.Date) >= start_time)

        if end_time:
            dict_list = dict_list.filter(db.cast(Dict.create_time, db.Date) <= end_time)
        total = dict_list.count()

        dict_list = dict_list.offset((page - 1) * limit).limit(limit).all()

        return jsonify({
            'code': 20000,
            'message': 'success',
            'items': [u.to_dict() for u in dict_list],
            'totalCount': total,
            'TotalPageCount': math.ceil(int(total / limit))
        })
    except Exception as e:
        print("get dicts error:", e)

    return jsonify({'code': 50001, 'message': "查询参数时发生错误"})


@r_dict.route('', methods=['POST'])
@api_auth.login_required
def add_dict():
    """
    @@@
    #### Args:
            {
                name: String(64)    #名称
                address: String(40)    #地址
                longitude: DECIMAL(10    #经度
                latitude: DECIMAL(10    #纬度
                status: TINYINT(unsigned=True)    #状态: 0:营业 1:未营业
                phone: String(40)    #联系电话
                desc: String(1023)    #场地介绍
                services: String(255)    #场地服务
                judgment: Boolean    #裁判服务: 0:否 1:是
                tips: String(255)    #标签
                open_time: String(16)    #开门时间
                close_time: String(16)    #关门时间
                day_price: DECIMAL(6    #白天单价
                night_price: DECIMAL(6    #夜晚单价
                we_day_price: DECIMAL(6    #周末白天单价
                we_night_price: DECIMAL(6    #周末夜晚单价
            }
    #### Returns::
            {'code': 20000, 'message': "参数添加成功"}
            {'code': 50001, 'message': "添加参数时发生错误"}
    """

    args = request.get_json()

    dict = Dict()
    try:
        set_field(dict, args)
        db.session.add(dict)
        db.session.commit()

        user_opt.send({
            "operation": "添加参数",
            "method": "参数管理",
            "params": dict.id,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "参数添加成功"})
    except Exception as e:
        db.session.rollback()
        print("add dict error:", e)

    return jsonify({'code': 50001, 'message': "添加参数时发生错误"})


@r_dict.route('/<int:pid>', methods=['DELETE'])
@api_auth.login_required
def remove_dict(pid):
    """
        @@@
        #### Args:
                dict/id
        #### Returns::
                {'code': 20000, 'message': "参数删除成功"}
                {'code': 50001, 'message': "删除参数时发生错误"}
        """
    try:
        Dict.query.filter_by(id=pid).delete()
        db.session.commit()

        user_opt.send({
            "operation": "删除参数",
            "method": "参数管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "参数删除成功"})
    except Exception as e:
        print("remove dict error:", e)
        return jsonify({
            'code': 50001,
            'message': "删除参数时发生错误"
        })


@r_dict.route('/<int:pid>', methods=['PUT'])
@api_auth.login_required
def edit_dict(pid):
    """
    @@@
    #### Args:
           dict/id
    #### Returns::
            {'code': 20000, 'message': "参数修改成功"}
            {'code': 50001, 'message': "修改参数时发生错误"}
    """
    args = request.get_json()
    try:
        dict = Dict.query.filter_by(id=pid).first()
        set_field(dict, args)

        db.session.commit()

        user_opt.send({
            "operation": "修改参数",
            "method": "参数管理",
            "params": pid,
            "user_id": g.user.id,
            "username": g.user.username
        })

        return jsonify({'code': 20000, 'message': "参数修改成功"})
    except Exception as e:
        db.session.rollback()
        print("edit dict error:", e)

    return jsonify({'code': 50001, 'message': "修改参数时发生错误"})


@r_dict.route('/<int:pid>', methods=['GET'])
@api_auth.login_required
def get_detail(pid):
    """
                    @@@
                    #### Args:
                           dict/id
                    #### Returns::
                            {
                                'code': 20000,
                                'items': [u.to_dict() for u in dict_list],
                            }
                """
    dict = Dict.query.filter_by(id=pid).first()
    if not dict:
        return jsonify({
            'code': 50002,
            'message': '查询参数不存在'
        })

    return jsonify({
        'code': 20000,
        'message': 'success',
        'items': dict.to_dict(),
    })

# >>>>> auto generate end <<<<<
